//
//  YBTaiHeartInputViewController.m
//  孕妙
//
//  Created by Raoy on 16/4/11.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "YBTaiHeartInputViewController.h"
#import "YBSelectPickerWindow.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "LMTPDecoder.h"

@interface YBTaiHeartInputViewController ()<UIPickerViewDelegate, UIPickerViewDataSource, CBCentralManagerDelegate, CBPeripheralDelegate>
//弹出手动输入窗口
@property (strong, nonatomic) YBSelectPickerWindow *pickerWindow;

@property (nonatomic, retain) NSMutableArray *peripherals;//搜到多少个蓝牙设备

@property (nonatomic, retain) CBCentralManager *mgr;//手机的蓝牙设备
@property (nonatomic, retain) CBPeripheral *peripheral;//外围的蓝牙设备，connectDeviceAtIndex函数中设置

@property (nonatomic, retain) CBCharacteristic * dataInteractCharacteristic;

@property (strong, nonatomic) dispatch_queue_t bluetoothQueue;
@property (nonatomic , strong) NSString * audioFilePath;

@property (strong , nonatomic) LMTPDecoder * decoder;

@property (nonatomic, assign) BOOL isConnected;
@property (nonatomic, copy)NSMutableArray *intArray; //选择器整数部分
@end

@implementation YBTaiHeartInputViewController
{

    NSString *selectIntStr;
    NSString *valueStr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =  SYColor(245, 245, 245);;
    self.title = @"记录胎心";
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"YB_backToSupper"  highIcon:nil target:self action:@selector(taiHeartclickLeftButtonToSupper2:)];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    
    [self.rightBtn addTarget:self action:@selector(taiHeartrigheBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
//    [self scanBle];

    //开始使用蓝牙设备测量
    [self.startbtn2 addTarget:self action:@selector(openBle:) forControlEvents:UIControlEventTouchUpInside];
    
    _decoder = [LMTPDecoder shareInstance];
    
    self.bluetoothQueue = dispatch_queue_create("com.lmtpdecoder.queue", NULL);
    
    //设置整数范围
    _intArray = [NSMutableArray array];
    for (int index = 30; index < 210; index++) {
        NSString *str = [NSString stringWithFormat:@"%d", index];
        [_intArray addObject:str];
    }

    //设置日期栏
    [self setTitle:@"请输入胎心率:" buyTitle:@"购买胎心仪" indexImage:5];
    //设置胎心
    valueStr = @" 次/min";
    [self createLabel:valueStr];
    // Do any additional setup after loading the view.
}

- (void)taiHeartrigheBtnClick:(id)sender
{
    self.fuGaiView.hidden = NO;
    if (_pickerWindow == nil) {
        _pickerWindow = [[YBSelectPickerWindow alloc] init];
        [_pickerWindow setInterFace:@"胎心率(次/min)"];
        _pickerWindow.selectPickerView.delegate = self;
        _pickerWindow.selectPickerView.dataSource = self;
    }else{
        
        _pickerWindow.hidden = NO;
    }
    
    [_pickerWindow.selectPickerView selectRow:70  inComponent:0 animated:YES];
    selectIntStr = _intArray[70];
    [_pickerWindow.selectPickerView reloadAllComponents];
    [_pickerWindow.sureBtn addTarget:self action:@selector(savetaiheartDataBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_pickerWindow.cancelBtn addTarget:self action:@selector(cancelBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)openBle:(UIButton *)button
{
    [self scanBle];
    
}

- (void)savetaiheartDataBtn:(UIButton *)btn
{
//    sleep(1);
    valueStr = nil;
    _pickerWindow.hidden = YES;
    self.fuGaiView.hidden = YES;
    valueStr = [NSString stringWithFormat:@"%@ 次/min", selectIntStr];
    [self createLabel:valueStr];
    [self.view setNeedsDisplay];
//    [self getUserParmaterData:[NSString stringWithFormat:@"%@",  selectIntStr] selectionValue:5 gaoxueya:nil];
}

- (void)cancelBtnClicked:(id)sender
{
    self.fuGaiView.hidden = YES;
}


- (void)taiHeartclickLeftButtonToSupper2:(id)sender
{
    self.pickerWindow.selectPickerView = nil;  //释放内存
    self.pickerWindow = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    NSLog(@"sfeawrr------");
    [super viewDidAppear:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- 连接蓝牙外设


- (NSMutableArray *)peripherals
{
    if (!_peripherals)
    {
        _peripherals = [NSMutableArray array];
    }
    
    return _peripherals;
}

- (CBCentralManager *)mgr
{
    if (!_mgr){
        
        self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    
    return _mgr;
}

- (void)scanBle
{
    if (self.useAddviceWindow.hidden == NO && self.useAddviceWindow != nil) {
        [self.mgr stopScan];
        self.peripheral = nil;
        self.mgr = nil;
        return;
    }
    [MBProgressHUD showMessage:@"正在搜索设备......"];
    self.startbtn2.isAccessibilityElement = NO;
    
    [self.mgr stopScan];
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    self.startbtn2.isAccessibilityElement = YES;
}



#pragma mark - UIPickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
//    NSLog(@"component = %d", component);
    return _intArray.count;
}
//- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
//{
//    return 10;
//}
//
//- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
//{
//    return 30;
//}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *tempStr = _intArray[row];
//    NSLog(@"tempStr = %d", row);
    return tempStr;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    selectIntStr = _intArray[row];
    
}



#pragma mark CBCentralManagerDelegate
// 手机蓝牙状态改变，或是程序刚执行时调用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state)
    {
            // 手机开启蓝牙
        case CBCentralManagerStatePoweredOn:
        {
            NSDictionary *options =[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
            [self.mgr scanForPeripheralsWithServices:nil options:options];//搜到设备后会有回调哦
        }
            break;
            // 手机关机蓝牙
        case CBCentralManagerStatePoweredOff:
        {
            self.isConnected = NO;
            [self.peripherals removeAllObjects];
            
        }
            break;
            
        default:
            NSLog(@"Central Manager did change state");
            break;
    }
}

//发现设备，
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"发现外设：%@  ", peripheral.name);
    
    [MBProgressHUD hideHUD];
    if (peripheral.name && peripheral.name.length > 3) {
        NSString *tempStr = [peripheral.name substringToIndex:3];
        NSLog(@"tempStr===%@", tempStr);
    
    
    
    
    
    if (![self.peripherals containsObject:peripheral]  && [tempStr isEqualToString:@"iFM"]){
        
        //设置外设代理
        peripheral.delegate = self;
        [self.peripherals addObject:peripheral];
    }else{
        
        return;
    }
    }
    NSLog(@"找到了 %@", peripheral.name);
    
    for (CBPeripheral *per in self.peripherals) {
        NSLog(@"外设：%@", per);
        if (per.state == NO) {
            self.peripheral = peripheral;
            [self.mgr connectPeripheral:self.peripheral options:nil];
        }
    }
}

//连接断开时
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    self.peripheral = nil;
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    [self.peripherals removeAllObjects];
    [self.buletoothImageView setImage:[UIImage imageNamed:@"蓝牙断开"]];
    NSLog(@"蓝牙连接已断开");
}

//连接设备成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    [self.mgr stopScan];
    [peripheral discoverServices:nil];
    NSLog(@"sucess");
    // 开始播放声音
    [self.decoder startRealTimeAudioPlyer];
    
}

#pragma mark --CBPeripheralDelegate
//搜索蓝牙服务,点击某个蓝牙设备后，开始搜索他的信息
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    
    for (CBService *service in peripheral.services)
    {
        NSString *ustring = [self CBUUIDToString:service.UUID];
        if ([service.UUID isEqual:[CBUUID UUIDWithString:ustring]]) {
            [peripheral discoverCharacteristics:nil forService:service];
        }
        
    }
}

#pragma mark --BLEUtility
- (NSString *) CBUUIDToString:(CBUUID *)inUUID
{
    unsigned char i[16];
    [inUUID.data getBytes:i length:16];
    if (inUUID.data.length == 2) {
        return [NSString stringWithFormat:@"%02hhx%02hhx",i[0],i[1]];
    }
    else {
        uint32_t g1 = ((i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3]);
        uint16_t g2 = ((i[4] << 8) | (i[5]));
        uint16_t g3 = ((i[6] << 8) | (i[7]));
        uint16_t g4 = ((i[8] << 8) | (i[9]));
        uint16_t g5 = ((i[10] << 8) | (i[11]));
        uint32_t g6 = ((i[12] << 24) | (i[13] << 16) | (i[14] << 8) | i[15]);
        return [NSString stringWithFormat:@"%08x-%04hx-%04hx-%04hx-%04hx%08x",g1,g2,g3,g4,g5,g6];
    }
    return nil;
}

//搜索蓝牙特征，是在选中某个蓝牙之后    UUID  service代表服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"discover bluetooth");
    if (self.useAddviceWindow.hidden == NO && self.useAddviceWindow != nil) {
        [self.mgr stopScan];
        self.peripheral = nil;
        self.mgr = nil;
        return;
    }
    [self.buletoothImageView setImage:[UIImage imageNamed:@"蓝牙连接"]];
    [self.view setNeedsDisplay];
    
    for (CBCharacteristic *characteristic in service.characteristics)
    {
        NSLog(@"Service: %@ :::::characteristic:%@", service.UUID, characteristic.UUID);
        
        if ([[self CBUUIDToString:characteristic.UUID] isEqualToString:@"fff1"])
        {
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            NSLog(@"------fff1");
        }
        
        if ([[self CBUUIDToString:characteristic.UUID] isEqualToString:@"fff2"])
            //if ([characteristic.UUID isEqual:_writeUUID])
        {
            NSLog(@"Discovered write Characteristic");
            NSLog(@"------fff2");
            self.dataInteractCharacteristic = characteristic;
        }
    }
}
// 读取蓝牙数据   CBCharacteristic代表特征
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (!characteristic) {
        return;
    }
    
    NSData *data = characteristic.value;
     LKCHeart * heart =  [self.decoder startDecoderWithCharacterData:data];
  
   
    if (heart) {
        valueStr = [NSString stringWithFormat:@" %ld 次/min",(long)heart.rate];
        [self createLabel:valueStr];
        NSLog(@" 胎心率 ： %ld       是否有fhr1： %ld",(long)heart.rate,(long)heart.isRate);
//        _tocoLable.text = [NSString stringWithFormat:    @"宫缩压力 ： %ld      是否有toco： %ld",(long)heart.tocoValue,(long)heart.isToco];
//        _batteryLable.text = [NSString stringWithFormat: @"电池电量 ： %ld      宫缩复位标记： %ld",(long)heart.battValue,(long)heart.tocoFlag];
//        _singleLable.text = [NSString stringWithFormat:  @"信号质量 ： %ld      手动胎动标记： %ld",(long)heart.signal,(long)heart.fmFlag];
        
    }
      NSLog(@" 胎心率 ： %ld       是否有fhr1： %ld",(long)heart.rate,(long)heart.isRate);
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
